import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  HttpCode,
  HttpStatus,
  Request,
  Headers,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { ThrottlerGuard } from '@nestjs/throttler';
import { NovelService } from './novel.service';
import { JwtService } from '@nestjs/jwt';
import { NovelChapterService } from './novel-chapter.service';
import { NovelTaskService } from './services/novel-task.service';
import { TaskRecoveryService } from './services/task-recovery.service';
import { CategoryMappingService } from './services/category-mapping.service';
import {
  CreateNovelDto,
  UpdateNovelDto,
  NovelQueryDto,
} from './dto/create-novel.dto';
import {
  CategoryMappingDto,
  BatchCategoryMappingDto,
  CategoryMappingResponseDto,
  MasterCategoryResponseDto,
  CategoryMappingQueryDto,
} from './dto/category-mapping.dto';

/**
 * 小说管理控制器
 * 提供小说、分类、章节的CRUD操作和查询功能
 */
@ApiTags('小说管理')
@Controller('novels')
@UseGuards(ThrottlerGuard)
export class NovelController {
  constructor(
    private novelService: NovelService,
    private chapterService: NovelChapterService,
    private novelTaskService: NovelTaskService,
    private taskRecoveryService: TaskRecoveryService,
    private categoryMappingService: CategoryMappingService,
    private jwtService: JwtService,
  ) {}

  // 分类管理 - 使用MasterCategory
  @Get('categories')
  @ApiOperation({ summary: '获取分类列表' })
  @ApiResponse({ status: 200, description: '获取成功' })
  async findCategories() {
    const masterCategories = await this.categoryMappingService.getAllMasterCategories();

    // 转换为前端需要的格式
    return masterCategories.map(category => ({
      id: category.id,
      name: category.name,
      code: category.id.toString(),
      sortOrder: category.sortOrder,
      status: category.status,
      description: category.description,
      keywords: category.keywords
    }));
  }

  // 小说管理
  @Post()
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.CREATED)
  async create(@Body() createNovelDto: CreateNovelDto) {
    return this.novelService.create(createNovelDto);
  }

  @Get()
  async findAll(@Query() query: NovelQueryDto) {
    return this.novelService.findAll(query);
  }

  @Get('search')
  async search(@Query() query: any) {
    const { keyword, page, limit } = query;
    return this.novelService.search(keyword, { page, limit });
  }

  @Get('popular')
  async findPopular(@Query() query: any) {
    const { limit = '10', categoryId } = query;
    return this.novelService.findPopularNovels(
      parseInt(limit, 10),
      categoryId ? parseInt(categoryId, 10) : undefined,
    );
  }

  @Get('latest')
  async findLatest(@Query() query: any) {
    const { limit = '10', categoryId } = query;
    return this.novelService.findLatestNovels(
      parseInt(limit, 10),
      categoryId ? parseInt(categoryId, 10) : undefined,
    );
  }

  @Get('recommended')
  async findRecommended(@Query() query: any) {
    const { limit = '10', categoryId } = query;
    return this.novelService.findRecommendedNovels(
      parseInt(limit, 10),
      categoryId ? parseInt(categoryId, 10) : undefined,
    );
  }

  @Get(':id')
  async findOne(@Param('id') id: string, @Headers() headers: any) {
    // 增加阅读量
    await this.novelService.incrementReadCount(parseInt(id, 10));

    let userId: number | undefined = undefined;

    // 尝试从Authorization header中获取用户信息
    const authHeader = headers.authorization;
    if (authHeader && authHeader.startsWith('Bearer ')) {
      try {
        const token = authHeader.substring(7);
        // 验证token并获取用户信息
        const decoded = this.jwtService.verify(token);
        // JWT token中的用户ID字段可能是userId或sub
        userId = decoded.userId || decoded.sub || decoded.id;
        console.log('成功从token获取到用户ID:', userId);
      } catch (error) {
        console.log('Token验证失败，继续以未登录用户处理');
        // token无效，继续以未登录用户处理
      }
    }

    return this.novelService.findOne(parseInt(id, 10), userId);
  }

  @Put(':id')
  @UseGuards(JwtAuthGuard)
  async update(
    @Param('id') id: string,
    @Body() updateNovelDto: UpdateNovelDto,
  ) {
    return this.novelService.update(parseInt(id, 10), updateNovelDto);
  }

  @Delete(':id')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async remove(@Param('id') id: string) {
    await this.novelService.remove(parseInt(id, 10));
    return { message: '小说删除成功' };
  }

  // 章节管理
  @Get(':id/chapters')
  async findChapters(@Param('id') novelId: string, @Query() query: any) {
    return this.chapterService.findByNovelId(parseInt(novelId, 10), query);
  }

  @Get(':id/chapters/first')
  async findFirstChapter(@Param('id') novelId: string) {
    return this.chapterService.findFirstChapter(parseInt(novelId, 10));
  }

  @Get(':id/chapters/last')
  async findLastChapter(@Param('id') novelId: string) {
    return this.chapterService.findLastChapter(parseInt(novelId, 10));
  }

  @Get(':novelId/chapters/:chapterNumber')
  async findChapter(
    @Param('novelId') novelId: string,
    @Param('chapterNumber') chapterNumber: string,
  ) {
    return this.chapterService.findByNovelAndChapter(
      parseInt(novelId, 10),
      parseInt(chapterNumber, 10),
    );
  }

  @Post(':id/chapters')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.CREATED)
  async createChapter(
    @Param('id') novelId: string,
    @Body() createChapterDto: any,
  ) {
    return this.chapterService.create({
      ...createChapterDto,
      novelId: parseInt(novelId, 10),
    });
  }

  @Get('chapters/:id')
  async findSingleChapter(@Param('id') id: string) {
    return this.chapterService.findOne(parseInt(id, 10));
  }

  @Put('chapters/:id')
  @UseGuards(JwtAuthGuard)
  async updateChapter(@Param('id') id: string, @Body() updateChapterDto: any) {
    return this.chapterService.update(parseInt(id, 10), updateChapterDto);
  }

  @Delete('chapters/:id')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async removeChapter(@Param('id') id: string) {
    await this.chapterService.remove(parseInt(id, 10));
    return { message: '章节删除成功' };
  }

  // 异步任务管理
  @Get('tasks/:taskId')
  async getTaskStatus(@Param('taskId') taskId: string) {
    const task = await this.novelTaskService.getTaskStatus(taskId);
    if (!task) {
      return {
        success: false,
        message: '任务不存在',
        data: null,
      };
    }

    return {
      success: true,
      message: '获取任务状态成功',
      data: task,
    };
  }

  @Get('tasks/:taskId/progress')
  async getTaskProgress(@Param('taskId') taskId: string) {
    const progress = await this.novelTaskService.getTaskProgress(taskId);
    if (!progress) {
      return {
        success: false,
        message: '任务不存在',
        data: null,
      };
    }

    return {
      success: true,
      message: '获取任务进度成功',
      data: progress,
    };
  }

  @Get('tasks')
  async getUserTasks(
    @Query('limit') limit: string = '20',
    @Query('offset') offset: string = '0',
  ) {
    const { tasks, total } = await this.novelTaskService.getUserTasks(
      undefined, // 暂时不区分用户
      parseInt(limit, 10),
      parseInt(offset, 10),
    );

    return {
      success: true,
      message: '获取任务列表成功',
      data: {
        tasks,
        total,
        limit: parseInt(limit, 10),
        offset: parseInt(offset, 10),
      },
    };
  }

  @Post('tasks/:taskId/retry')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async retryTask(@Param('taskId') taskId: string) {
    const success = await this.novelTaskService.retryFailedTask(taskId);
    if (!success) {
      return {
        success: false,
        message: '任务重试失败，任务不存在或状态不允许重试',
      };
    }

    return {
      success: true,
      message: '任务已重新提交到队列',
    };
  }

  @Delete('tasks/:taskId')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async cancelTask(@Param('taskId') taskId: string) {
    const success = await this.novelTaskService.cancelTask(taskId);
    if (!success) {
      return {
        success: false,
        message: '任务取消失败，任务不存在或已开始处理',
      };
    }

    return {
      success: true,
      message: '任务已成功取消',
    };
  }

  // 任务恢复管理
  @Post('tasks/recover')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async recoverStuckTasks() {
    const result = await this.taskRecoveryService.manualRecovery();
    return {
      success: true,
      message: '任务恢复完成',
      data: result,
    };
  }

  // 分类映射管理
  @Get('categories/mapping/initialize')
  @ApiOperation({ summary: '初始化分类映射数据' })
  @ApiResponse({ status: 200, description: '初始化完成' })
  async initializeCategoryMappings() {
    await this.categoryMappingService.initializeAll();
    return {
      success: true,
      message: '分类映射数据初始化完成',
    };
  }

  @Get('categories/mapping/master')
  @ApiOperation({ summary: '获取所有母分类' })
  @ApiResponse({ status: 200, description: '获取成功', type: [MasterCategoryResponseDto] })
  async getMasterCategories(): Promise<MasterCategoryResponseDto[]> {
    return await this.categoryMappingService.getAllMasterCategories();
  }

  @Get('categories/mapping/:site')
  @ApiOperation({ summary: '获取指定站点的分类映射' })
  @ApiResponse({ status: 200, description: '获取成功', type: [CategoryMappingResponseDto] })
  async getSiteMappings(@Param('site') site: string) {
    const mappings = await this.categoryMappingService.getSiteMappings(site);
    return mappings.map(mapping => ({
      site: mapping.site,
      siteCategory: mapping.siteCategory,
      masterCategory: {
        id: mapping.masterCategory.id,
        name: mapping.masterCategory.name,
        keywords: mapping.masterCategory.keywords,
        description: mapping.masterCategory.description,
      },
      description: mapping.description,
    }));
  }

  @Post('categories/mapping')
  @ApiOperation({ summary: '添加新的分类映射' })
  @ApiResponse({ status: 201, description: '添加成功', type: CategoryMappingResponseDto })
  @UseGuards(JwtAuthGuard)
  async addCategoryMapping(@Body() mappingDto: CategoryMappingDto) {
    const mapping = await this.categoryMappingService.addSiteMapping(
      mappingDto.site,
      mappingDto.siteCategory,
      mappingDto.masterId,
      mappingDto.description,
    );

    return {
      site: mapping.site,
      siteCategory: mapping.siteCategory,
      masterCategory: {
        id: mapping.masterId,
        name: '', // 需要查询母分类信息
        keywords: '',
        description: undefined,
      },
      description: mapping.description,
    };
  }

  @Post('categories/mapping/batch')
  @ApiOperation({ summary: '批量添加分类映射' })
  @ApiResponse({ status: 201, description: '批量添加成功' })
  @UseGuards(JwtAuthGuard)
  async addBatchCategoryMappings(@Body() batchDto: BatchCategoryMappingDto) {
    const results: any[] = [];

    for (const mappingDto of batchDto.mappings) {
      try {
        const mapping = await this.categoryMappingService.addSiteMapping(
          mappingDto.site,
          mappingDto.siteCategory,
          mappingDto.masterId,
          mappingDto.description,
        );

        results.push({
          success: true,
          site: mapping.site,
          siteCategory: mapping.siteCategory,
        });
      } catch (error) {
        results.push({
          success: false,
          site: mappingDto.site,
          siteCategory: mappingDto.siteCategory,
          error: error.message,
        });
      }
    }

    return {
      success: true,
      message: '批量处理完成',
      data: results,
    };
  }
}
